package com.fay.mymiaosha.controller;

import com.fay.mymiaosha.exception.BizException;
import com.fay.mymiaosha.response.CommonReturnType;
import com.fay.mymiaosha.response.EmBizError;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/3/15 15:10
 * @Version 1.0
 */
public class BaseController {

    //定义内容类型常量
    public static final String CONTENT_TYPE_FORMED = "application/x-www-form-urlencoded";

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    // 返回的Object会去寻找本地页面文件
    @ResponseBody
    public Object handlerException(HttpServletRequest request, Exception ex) {
        Map<String, Object> responseData = new HashMap<>();
        if (ex instanceof BizException) {
            BizException bizException = (BizException) ex;
            responseData.put("errCode", bizException.gerErrCode());
            responseData.put("errMsg", bizException.getErrMsg());
        } else {
            responseData.put("errCode", EmBizError.UNKNOWN_ERROR.gerErrCode());
            responseData.put("errMsg", EmBizError.UNKNOWN_ERROR.getErrMsg());
        }
        // 之所以不直接将Enum传为返回的data，因为@ResponseBody默认序列化方式会把Enum的定义序列化，
        // 而不是各个属性值序列化，拿不到errCode和errMsg
        return CommonReturnType.create(responseData, "fail");
    }
}
